package com.itfreer.data.general.utils;

import com.itfreer.data.general.ITable;
import com.itfreer.data.general.cache.LocalCache;
import com.itfreer.utils.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * 定义表处理辅助类
 */
public class TablesUtils {
	
	/**
	 * 获取当前的所有表信息，以树的形式展示
	 * @return
	 */
	public static List<TreeNode> getTables() {
		HashMap<String, ITable> tableCache = LocalCache.getTableCache();
		Set<String> keys = tableCache.keySet();
		List<TreeNode> result = new ArrayList<TreeNode>();
		HashMap<String, TreeNode> treeGroup = new HashMap<String, TreeNode>();
		for (String key : keys) {
			ITable pTable = tableCache.get(key);
			String groupKey = pTable.getTableGroup();
			TreeNode pTableNode = null;
			if (treeGroup.containsKey(groupKey)) {
				pTableNode = treeGroup.get(groupKey);
			} else {
				pTableNode = new TreeNode();
				pTableNode.setid(groupKey);
				pTableNode.setText(groupKey);
				result.add(pTableNode);
				pTableNode.setChildren(new ArrayList<TreeNode>());
				treeGroup.put(groupKey, pTableNode);
			}
			TreeNode tableNode = new TreeNode();
			tableNode.setid(pTable.getMetadataTableName());
			tableNode.setText(pTable.getMetadataTableAliasName());
			tableNode.setState("open");
			pTableNode.getChildren().add(tableNode);
		}
		return result;
	}

	/**
	 * 获取表信息
	 * @return
	 */
	public static HashMap<String, String> getTablesMap(){
		HashMap<String, ITable> tableCache = LocalCache.getTableCache();
		Set<String> keys = tableCache.keySet();
		HashMap<String, String> result = new LinkedHashMap<String, String>();
		for (String key : keys) {
			ITable pTable = tableCache.get(key);
			result.put(key, pTable.getMetadataTableAliasName());
		}
		return result;
	}
}